<template>
  <ul class="todo-main">
    <Item
      v-for="todo in todoList"
      :key="todo.id"
      v-bind="todo"
      @deleteTodo="deleteTodoHandel"
      @changeChecked="changeCheckedHandel"
    />
  </ul>
</template>

<script>
import { v4 as uuidV4 } from "uuid";
import Item from "./Item/Item.vue";
export default {
  name: "List",
  data() {
    return {
      todoList: [
        { id: uuidV4(), thing: "唱", done: false },
        { id: uuidV4(), thing: "跳", done: false },
        { id: uuidV4(), thing: "rap", done: false },
      ],
    };
  },
  components: {
    Item,
  },
  methods: {
    //删除单个逻辑
    deleteTodoHandel(id) {
      this.todoList = this.todoList.filter((item) => item.id !== id);
    },
    //单选框
    changeCheckedHandel(id) {
      this.todoList = this.todoList.map((item) =>
        item.id === id ? { ...item, done: !item.done } : item
      );
    },
  },
  mounted() {
    //添加逻辑
    this.$bus.$on("getNewTodoList", (newTodoList) => {
      this.todoList.unshift(newTodoList);
    });
    //给Footer传入todoList
    this.$bus.$emit("todoList", this.todoList);
    // 已完成数量
    this.$bus.$emit(
      "finished",
      this.todoList.filter((item) => item.done).length
    );
    //全选逻辑
    this.$bus.$on("allChecked", (e) => {
      this.todoList = this.todoList.map((item) => ({
        ...item,
        done : e.target.checked,
      }));
    });
    //全部删除逻辑
    this.$bus.$on("deleteAll",() => {
        this.todoList = this.todoList.filter((item) => !item.done)
    })
  },

  watch: {
    todoList: {
      deep: true,
      handler() {
        this.$bus.$emit(
          "finished",
          this.todoList.filter((item) => item.done).length
        );

        this.$bus.$emit("todoList", this.todoList);

    //     this.$bus.$on("allChecked", (e) => {
    //    this.todoList = this.todoList.map((item) => ({
    //     ...item,
    //     done : e.target.checked,
    //   }));
    // })
      },
    },
  },
};
</script>

<style scoped>
/*main*/
.todo-main {
  margin-left: 0px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding: 0px;
}

.todo-empty {
  height: 40px;
  line-height: 40px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding-left: 5px;
  margin-top: 10px;
}
</style>